import { register, login } from "@/api";

export default {
  namespaced: true,
  state: {
    info: JSON.parse(localStorage.getItem("user")) || null,
  },
  mutations: {
    updateUserInfo: (state, data) => {
      state.info = data;

      localStorage.setItem("user", JSON.stringify(data));
    },

    removeUserInfo: (state) => {
      state.info = {};
      localStorage.removeItem("user");
    },
  },
  actions: {
    register: (context, data) => {
      return register(data);
    },

    login: async ({ commit }, data) => {
      let { data: userData, headers } = await login(data);
      commit("updateUserInfo", {
        id: userData.id,
        name: userData.name,
        authorization: headers.authorization,
      });
    },

    logout: ({ commit }) => {
      commit("removeUserInfo");
    },
  },
};
